import { Modal,Row, Col, Button, InputNumber } from "antd";
import React from "react";
import { FormSetDiv } from "./style.js";
import FieldSetLeft from "./FieldSetLeft";
import FieldSetCenter from "./FieldSetCenter";
import FieldSetRight from "./FieldSetRight";
import { getUuid } from "@/utils/utils.js";
import picture from "@/assets/homeImgV2/picture.png"
import {arrayMoveImmutable} from 'array-move';
import Sortable from 'sortablejs';
import { ChromePicker } from "react-color";
import Preview from "./preview.js";
import testData from "./testData.js";
import styles from "../index.less"

const fieldTypeObj = {
  text:{
    text:"文本域",
    styles:{
      color:"#000000",
      fontWeight:"normal",
      fontSize:'14',
      marginTop:0,
      marginBottom:0,
      marginLeft:0,
      marginRight:0,
      display:"inline-block"
    }
  },
  picture:{
    text:"上传图片",
    src:picture,
    styles:{
      width:80,
      height:80,
      marginTop:0,
      marginBottom:0,
      marginLeft:0,
      marginRight:0,
      verticalAlign:"middle"
    }
  },
  tag:{
    text:"标签",
    styles:{
      display:"inline-block",
      border:"1px solid #cccccc",
      backgroundColor:"",
      borderColor:"",
      color:"",
      width:"",
      height:"",
      textAlign:"left",
      borderRadius:"4",
      fontSize:"14",
      lineHeight:"unset",
      padding:"4px 8px",
      textAlign:"left"
    }
  },
  cols:{
    text:"栅格",
    colList:[]
  },
}

class CardConfig extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      currentField:null,
      fieldList:[],
      domKey:getUuid(),
      cardBg:"#f3f6fc",
      chromePickerShow:'none',
      previewVisible:false,
      borderColor:"#f3f6fc",
      showType:'',
      pageSize:3
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    // this.getDetail()
  }

  getDetail = (configurationCardStyle) => {
    
    this.setState({
      visible:true,
      fieldList:configurationCardStyle.fieldList ? configurationCardStyle.fieldList : [],
      cardBg:configurationCardStyle.cardBg ? configurationCardStyle.cardBg : "#f3f6fc",
      borderColor:configurationCardStyle.borderColor ? configurationCardStyle.borderColor : "#f3f6fc",
      pageSize:configurationCardStyle.pageSize ? configurationCardStyle.pageSize : 3
    },() => {
      this.reCreateSortBox()
    })
  }

  doCancel = () => {
    this.setState({
      visible:false
    })
  }

  doOk = () => {
    const data = this.getResultData()
    this.props.setCardConfigData(data)
    this.doCancel()
  }

  setFieldList = (fieldItem) => {
    const { fieldList } = this.state;
    const fromItem = fieldItem.from;
    const fromType = fromItem.getAttribute("id")

    const toItem = fieldItem.to;
    const toType = toItem.getAttribute("id")
    
    const item = fieldItem.item
    //会有3个class ant-col ant-col-8 text/picture/tag
    const itemType = item.getAttribute("class").split(" ")
    console.log(itemType);
    console.log('从===',fromType);
    console.log('到===',toType);
    console.log('自===',itemType);

    const leftItems = ['fieldItems','controlItems','apiItems']
    //情况1：leftItems -> itemsRight
    //  为第一层数据，直接在fieldList内新增
    if(leftItems.indexOf(fromType) != -1 && toType == 'itemsRight'){
      const newList = this.addField(fieldList,fieldItem);
      console.log('新增后的数据为===',newList);
      this.setState({
        fieldList:JSON.parse(JSON.stringify(newList))
      },() => {
        item.remove()
      }) 
    }

    //情况2：leftItems -> 对应id的容器
    //  为子数据，寻找其对应的list内新增
    if(leftItems.indexOf(fromType) != -1 && toType != 'itemsRight'){
      //修改colList中对应id的fieldList
      this.updateFieldItem("colList",fieldItem,{type:'addFieldByLeftItems',id:toType})
      item.remove()
    }       
  }

  addField = (list,fieldItem) => {
    const dataList = JSON.parse(JSON.stringify(list));
    const item = fieldItem.item
    const itemType = item.getAttribute("class").split(" ")
    //根据拖拽的控件类型，来新增不同的数据
    //form和api类型的，使用text原始数据
    //其他类型的，使用其对应的原始数据
    const fieldOrg = itemType[2] == 'form' || itemType[2] == 'api' ? fieldTypeObj.text : fieldTypeObj[itemType[2]]
    let obj = {
      fieldType:itemType[2],
      ...fieldOrg,
      text:item.innerText,
      id:getUuid(),
    }
    if(obj.fieldType === 'cols'){
      obj.colList = [
        {
          span:24,
          fieldList:[],
          id:getUuid(),
          key:getUuid(),
          textAlign:"left"
        }
      ]
    }
    dataList.push(obj)
    //若创建的元素为栅格，则需要创建对应的拖拽容器
    if(itemType[2] === 'cols'){
      setTimeout(() => {
        this.FieldSetCenter.createSortBox(obj.colList[0].id)
      },100)
    }
   
    return dataList
  }

  setCurrentField = (currentField) => {
    const { fieldList } = this.state;
    const currentId = currentField.item.getAttribute("id")
    const fieldItem = this.recursiveById(JSON.parse(JSON.stringify(fieldList)),currentId)
    this.setState({
      currentField:fieldItem
    })
  }

  /**
   * 
   * @param {*需要修改的属性} key 
   * @param {*需要修改的值} value 
   * @param {*栅格列操作的索引值} colListInfo 
   */
  updateFieldItem = (key,value,colListInfo) => {
    const { fieldList,currentField } = this.state;
    const currentId = colListInfo && colListInfo.id ? colListInfo.id : currentField.id
    const newList = this.updateFieldsList(JSON.parse(JSON.stringify(fieldList)),currentId,key,value,[],colListInfo)
    this.setState({
      fieldList:JSON.parse(JSON.stringify(newList))
    })
  }

  //递归修改元素值
  updateFieldsList = (data, currentId,key,value, arr = [],colListInfo) => {
    for (let i = 0; i < data.length; i++) {
      //处理改变styles中属性时，会改变源数组的问题
      let item = data[i]
      if(item.id == currentId){
        switch(key){
          case 'text':
          case 'src':
            //修改标题或图片地址
            item[key] = value
            break;
          case 'colList':
            //修改栅格内容
            if(colListInfo.type === 'add'){
              //1.新增栅格
              let obj = {
                span:24,
                fieldList:[],
                id:getUuid(),
                key:getUuid(),//用于更新位置后的重绘dom
                textAlign:"left"
              }
              item.colList.push(obj)
              //新增栅格的同时，需要新增对应的拖拽容器
              setTimeout(() => {
                this.FieldSetCenter.createSortBox(obj.id)
              },100)
            }
            if(colListInfo.type === 'edit'){
              //2.修改栅格占比大小
              item.colList[colListInfo.index].span = value ? value : 1
            }
            if(colListInfo.type === 'editText'){
              //2.修改栅格内文字对齐方式
              item.colList[colListInfo.index].textAlign = value ? value : 'left'
            }
            if(colListInfo.type === 'addFieldByLeftItems'){
              //3.从左侧新增栅格内的控件 - 需新增控件数据
              item.fieldList = this.addField(JSON.parse(JSON.stringify(item.fieldList)),value)
            }
            if(colListInfo.type === 'sortField'){
              //4.栅格内控件位置修改
              item.fieldList = value
            }
            if(colListInfo.type === 'removeCol'){
              //5.删除栅格
              item.colList = item.colList.filter(f => f.id != value)
            }
            break;
          default:
            //修改styles中的属性
            item['styles'][key] = value
            break;
        }

        //改变list的同时，修改current数据
        this.setState({
          currentField:item
        })
        
        // arr.push(item)
        // return
      }
      if(item.colList && item.colList.length > 0){
        this.updateFieldsList(item.colList,currentId,key,value,arr,colListInfo)
      }
      if(item.fieldList && item.fieldList.length > 0){
        this.updateFieldsList(item.fieldList,currentId,key,value,arr,colListInfo)
      }
    }
    return data
  }

  //递归查询获取对应id的数据
  recursiveById = (data,id) => {
    for (let item of data) {
      if (item.id === id) {
        return item;
      }
      if(item?.fieldList?.length){
        let node = this.recursiveById(item.fieldList, id, item);
        if (node) {
          return node;
        }
      }
      if (item?.colList?.length) {
        let node = this.recursiveById(item.colList, id, item);
        if (node) {
          return node;
        }
      }
    }
    return null
  }
  

  //点击非节点 current设为空
  setCurrentNull = () => {
    this.setState({
      currentField:null
    })
  }

  //移动节点排序
  dragEvt = (evt) => {
    const list = JSON.parse(JSON.stringify(this.state.fieldList))

    const toItem = evt.to;
    const toId = toItem.getAttribute("id")

    console.log('容器id====',toId);
    //新旧索引不同 说明发生了顺序变换
    if(evt.oldIndex != evt.newIndex){
      //1.当前容器的id为itemsRight 表示在数据的第一层进行排序
      if(toId === 'itemsRight'){
        const newArray = arrayMoveImmutable(list, evt.oldIndex, evt.newIndex);
        this.setState({
          fieldList:JSON.parse(JSON.stringify(newArray)),
        })
        
      }else{
      //2.当前容器的id为具体id值 表示数据在内部colList内进行排序 需要递归找到当前容器层的数据 然后修改其fieldList
        const boxData = this.recursiveById(list,toId)
        const newFields = arrayMoveImmutable(boxData.fieldList, evt.oldIndex, evt.newIndex);
        //获取到该容器新的fieldList之后 需要递归修改该容器的fieldList字段值
        this.updateFieldItem("colList",newFields,{type:'sortField',id:toId})
      }
      
      //3.位置修改之后 dom随之修改 每一个容器都需要重新绘制sortable
      this.reCreateSortBox()
    }
  }

  reCreateSortBox = () => {
    const list = JSON.parse(JSON.stringify(this.state.fieldList))
    const newList = this.getAllBoxId(list).data
    this.setState({
      domKey:getUuid(),
      fieldList:JSON.parse(JSON.stringify(newList))
    },() => {
      // this.FieldSetCenter.initSort()
      this.getAllBoxId(list).boxIds.map(b => {
        this.FieldSetCenter.createSortBox(b)
      })
    })
  }

  //递归获取所有拖拽容器id，用于更改顺序后的重绘dom
  getAllBoxId = (data,arr=[]) => {
    for(let item of data){
      if(item.key){
        item.key = getUuid()
        arr.push(item.id)
      }
      if(item?.fieldList?.length){
        this.getAllBoxId(item.fieldList,arr)
      }
      if (item?.colList?.length) {
        this.getAllBoxId(item.colList,arr)
      }
    }
    return {data,boxIds:arr}
  }

  rgbaToHexColor(rgbaArray, alphaMaxVal = 1) {
    //补位警号
    return "#" + rgbaArray.map((chanel, index) => {
      let hexNum="";
      if (index === 3) {
        //这是alpha通道
        hexNum= Number(Math.round(chanel * 255/alphaMaxVal)).toString(16);
      }else {
        //普通通道直接转换
        hexNum=Number(chanel).toString(16)
      }
      return hexNum.length===1?'0'+hexNum:hexNum;//这里解决了部分通道数字小于10的情况进行补位
    }).join("");
  }

  doCancelPreview = () => {
    this.setState({
      previewVisible:false
    })
  }

  removeFieldById = (currentId) => {
    const list = JSON.parse(JSON.stringify(this.state.fieldList))
    const removeNode = (data,id) => {
      for(const i in data){
        if(data[i].id === id){
          data.splice(i,1)
        }
        if(data[i]?.fieldList?.length){
          removeNode(data[i].fieldList,id)
        }
        if (data[i]?.colList?.length) {
          removeNode(data[i].colList,id)
        }
      }
      return data
    }
    
    const newList = removeNode(list,currentId);
    this.setState({
      fieldList:JSON.parse(JSON.stringify(newList)),
      currentField:null
    })
  }

  getResultData = () => {
    const { cardBg,borderColor,fieldList,pageSize } = this.state;
    let obj = {
      cardBg,borderColor,fieldList,pageSize:pageSize ? pageSize : 3
    }
    return obj
  }

  setCurrentRow = (rowItem) => {
    console.log(rowItem);
    this.setState({
      currentField:rowItem
    })
  }

  render(){
    const { visible,currentField,fieldList,domKey,cardBg,chromePickerShow,previewVisible,showType,borderColor ,pageSize} = this.state;
    const { leftFieldList,leftApiList } = this.props;
    return(
      <Modal
        title='卡片配置'
        visible={visible}
        onCancel={this.doCancel}
        onOk={this.doOk}
        width={'80vw'}
        keyboard={false}
        maskClosable={false}
      >
        <div className={styles.cardSet}>
          <span>卡片背景色:</span>
          <span style={{display:"inline-block",width:10,height:10,background:cardBg}}></span><span style={{marginLeft:5,cursor:"pointer"}} onClick={() => {
            this.setState({
              chromePickerShow:'block',
              showType:"cardBg"
            })
          }}>{cardBg}
          </span>
          <span style={{marginLeft:15}}>卡片边框颜色:</span>
          <span style={{display:"inline-block",width:10,height:10,background:borderColor}}></span><span style={{marginLeft:5,cursor:"pointer"}} onClick={() => {
            this.setState({
              chromePickerShow:'block',
              showType:"borderColor"
            })
          }}>{borderColor}
          </span>
          <label style={{marginLeft:15,marginRight:5}}>每页对话框展示卡片数量</label>
          <InputNumber min={3} precision={0} value={pageSize} onChange={value => this.setState({pageSize:value})} />
          <Button icon="eye" size="small" onClick={() => this.setState({previewVisible:true})} style={{marginLeft:15}}>预览</Button>
          <div style={{display:chromePickerShow,position:"absolute",zIndex:"99999999999"}}>
            <ChromePicker
              color={showType === 'cardBg' ? cardBg : borderColor}
              onChangeComplete={(color) => {
                showType === 'cardBg' ? 
                this.setState({
                  cardBg: this.rgbaToHexColor([color.rgb.r,color.rgb.g,color.rgb.b,color.rgb.a]),
                  chromePickerShow:'none'
                })
                :
                this.setState({
                  borderColor: this.rgbaToHexColor([color.rgb.r,color.rgb.g,color.rgb.b,color.rgb.a]),
                  chromePickerShow:'none'
                })
              }}
            />
          </div>
        </div>
        <FormSetDiv>
          <div className="fieldSet-main">
            <Row className="fieldSet-main-content">
              <Col span={6} className="fieldSet-main-content-left" onClick={this.setCurrentNull}>
                <FieldSetLeft leftApiList={leftApiList} leftFieldList={leftFieldList} />
              </Col>
              <Col span={12} className="fieldSet-main-content-center" style={{background:cardBg,border:'1px solid',borderColor,borderRadius:6}}>
                <FieldSetCenter
                  setCurrentField={this.setCurrentField}
                  setFieldList={this.setFieldList}
                  fieldList={fieldList}
                  currentField={currentField}
                  onRef={ref => this.FieldSetCenter = ref}
                  dragEvt={this.dragEvt}
                  domKey={domKey}
                  removeFieldById={this.removeFieldById}
                  setCurrentRow={this.setCurrentRow}
                />
              </Col>
              <Col span={6} className="fieldSet-main-content-right">
                <FieldSetRight
                  currentField={currentField}
                  updateFieldItem={this.updateFieldItem}
                />
              </Col>
            </Row>
          </div>
        </FormSetDiv>

        <Preview visible={previewVisible} doCancelPreview={this.doCancelPreview} fieldList={fieldList} cardBg={cardBg} borderColor={borderColor} />
      </Modal>
    )
  }
}

export default CardConfig